import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an8 from '@mmstudio/an000008';
import an48 from '@mmstudio/an000048';
import { tbteacherlist } from '../../../atoms/db';


const logger = anylogger('pages/api/professional/course/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = ITbteacherlist;

/**
 * 新增服务
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const body = req.body as Message;

		if (!body
			|| !body.picture
			|| !body.teacher_id
			|| !body.teachername
			|| !body.telephone
			|| !body.degree
		) {
			res.status(200).json({
				ok: false,
				message: '缺少必要的参数'
			});
			return;
		}
		const course = await tbteacherlist().first('*').where({
			teacher_id: body.teacher_id,
			teachername: body.teachername,
		});
		if (course) {
			res.status(200).json({ ok: false, message: '教师已存在' });
			return;
		}
		const teacher_id = an8();
		await tbteacherlist().insert({
			...body,
			teacher_id
		});
		res.status(200).json({ ok: true });
	} catch (error) {
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
